package org.zero.db;

import java.sql.Connection;

/**
 * 事务管理器
 *
 * @author Zero
 */
public class TransactionManager {
    private TransactionManager() {
    }

    private static final ThreadLocal<Connection> CONNECTION_THREAD_LOCAL = new ThreadLocal<>();

    public static void setConnection(Connection connection) {
        check(connection);
        CONNECTION_THREAD_LOCAL.set(connection);
    }

    public static Connection getConnectionWithCheck() {
        Connection connection = getConnection();
        check(connection);
        return connection;
    }

    public static Connection getConnection() {
        return CONNECTION_THREAD_LOCAL.get();
    }

    public static void begin() {
        try {
            getConnectionWithCheck().setAutoCommit(false);
        } catch (Exception e) {
            throw new RuntimeException("begin transaction error", e);
        }

    }

    public static void commit() {
        try {
            getConnectionWithCheck().commit();
        } catch (Exception e) {
            throw new RuntimeException("commit transaction error", e);
        }

    }

    public static void rollback() {
        try {
            getConnectionWithCheck().rollback();
        } catch (Exception e) {
            throw new RuntimeException("rollback transaction error", e);
        }
    }

    public static void remove() {
        CONNECTION_THREAD_LOCAL.remove();
    }

    private static void check(Connection connection) {
        try {
            if (connection == null) {
                throw new RuntimeException("connection is null!!!");
            }
            if (connection.isClosed()) {
                throw new RuntimeException("connection is closed!!!");
            }
            if (connection.isReadOnly()) {
                throw new RuntimeException("connection is read only!!!");
            }
        } catch (Exception e) {
            throw new RuntimeException("check connection is error!!!", e);
        }
    }
}
